//
//  ST_PairsUserModel.swift
//  btvideo
//
//  Created by mac on 2020/1/9.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import HandyJSON
import SwiftyJSON
import SwiftyUserDefaults

//MARK: -  Cell 类型
protocol ST_CellTypeProtocol {
    var cellType: ST_PairsCenterCellType { get }
    
    var pairsCellHeight: CGFloat { get set}
}

/**
 个人中心Cell 样式
 */
enum ST_PairsCenterCellType {
    
    /**
     key value 样式
     */
    case textMap
    //    /**
    //    只有key
    //    */
    //    case textSupplement
    /**
     只有文本
     */
    case text
    
    /**
     副标题
     */
    case subTitle
    /**
     特质详情
     */
    case peculiarityDetail
    /**
     特质类别
     */
    case peculiaritySection
    /**
     日常
     */
    case daily
    
    //    新增的
    /**
     有相互匹配的功能
     */
    case peculiarityMatch
    
    
    /**
     只有我喜欢的特质
     */
    case onlyMyLovePeculiarity
    
    
    /**
     只有她喜欢的我特质
     */
    case onlyLoveMePeculiarity
    
    
    /**
     只有她喜欢的特质，我没有
     */
    case onlyLikePeculiarityExcludeMe
    
    /**
     加载中
     */
    case loading
}

/**
 个人中心Section 样式
 */
enum ST_PairsCenterSectionType {
    
    /**
     头部
     */
    case header
    /**
     尾部
     */
    case footer
    /**
     头部 【圆角】
     */
    case cornerHeader
    /**
     尾部 【圆角】
     */
    case cornerFooter
}

//MARK: - View Model
class ST_PairsUserCenterViewModel: NSObject {
    
    var is_friends = false{
        didSet{
            tableHeaderViewModel.is_friends = is_friends
        }
    }
    
    var isSentProps = false
    
    var ta = ""
    
    var tableHeaderViewModel = ST_PairsMyCenterHeaderViewModel()
    
    var datasets = [ST_PairsUserCenterSetionSet]()
    
    /**
     0 none
     1 语音匹配中
     2 视频匹配中
     3 忙碌
     */
    var liveBeautyStatue = 0
    /**
     附加匹配特质
     */
    func appendMatch(json:JSON){
        
        let matchModel = ST_PairsCenterMatchPecCellModel.init(fromJson: json, gender: self.ta)
        
        //        匹配特质样式
        if matchModel.loveMeArray.count > 0 &&  matchModel.myLoveArray.count > 0{
            
            let Set = ST_PairsUserCenterSetionSet()
            
            Set.list = [matchModel]
            
            Set.displayFooter = false
            
            Set.displayHeader = false
            
            //                model.datasets.append(Set)
            
            self.datasets[0] = Set
            
        }
        //        喜欢我特质 样式
        else if matchModel.loveMeArray.count > 0{
            
            let Set = ST_PairsUserCenterSetionSet()
            
            Set.list = [ST_PairsCenterOnlyLoveMePecCellModel.init(fromJson: json, gender: ta)]
            
            Set.displayFooter = false
            
            Set.displayHeader = false
            
            self.datasets[0] = Set
            
        }
        //        我喜欢特质 样式
        else if matchModel.myLoveArray.count > 0{
            
            let Set = ST_PairsUserCenterSetionSet()
            
            Set.list = [ST_PairsCenterOnlyMyLovePecCellModel.init(fromJson: json, gender: ta)]
            
            Set.displayFooter = false
            
            Set.displayHeader = false
            
            self.datasets[0] = Set
        }
        //        展示TA喜欢的特质
        else{
            
            let likeArray = json["like_feature"].arrayValue.map { (item) -> ST_PairsPeculiarity in
                return ST_PairsPeculiarity.deserialize(from: item.rawString() ?? "") ??  ST_PairsPeculiarity()
            }
            //        展示TA喜欢的特质
            
            if likeArray.count > 0{
                
                let Set = ST_PairsUserCenterSetionSet()
                
                let likeSet = ST_PairsLovePeculiaritySetsModel()
                
                likeSet.data_array = likeArray
                
                likeSet.showMoreDataBtn = json["like_feature_total"].intValue > 8
                
                likeSet.accid = tableHeaderViewModel.accid
                likeSet.ta = ta
                
                if likeSet.data_array.count < 5{
                    likeSet.pairsCellHeight = ST_PairsLoveMultiST_PeculiarityCell.itemViewHeight + 61 + 25
                    //                    自己不展示 我符合
                    if ta == "我"{
                        likeSet.pairsCellHeight = PairsMyLoveMultiST_PeculiarityCell.itemViewHeight + 61 + 25
                    }else{
                        likeSet.pairsCellHeight = ST_PairsLoveMultiST_PeculiarityCell.itemViewHeight + 61 + 25
                    }
                }
                //                显示更多
                else if likeSet.showMoreDataBtn {
                    if ta == "我"{
                        likeSet.pairsCellHeight = PairsMyLoveMultiST_PeculiarityCell.itemViewHeight * 2 + 61 + 25 + 35 + 20
                    }else{
                        likeSet.pairsCellHeight = ST_PairsLoveMultiST_PeculiarityCell.itemViewHeight * 2 + 61 + 25 + 35 + 20
                    }
                    
                }else{
                    
                    if ta == "我"{
                        likeSet.pairsCellHeight = PairsMyLoveMultiST_PeculiarityCell.itemViewHeight * 2 + 61 + 30 + 5
                    }else{
                        likeSet.pairsCellHeight = ST_PairsLoveMultiST_PeculiarityCell.itemViewHeight * 2 + 61 + 30 + 5
                    }
                    
                    
                }
                
                likeSet.pairsCellHeight += 1
                
                Set.list = [likeSet]
                
                Set.displayFooter = false
                
                Set.displayHeader = false
                
                self.datasets[0] = Set
            }
//            所有都为空
            else{
                
                self.datasets.removeFirst()
                
                
            }
        }
        
    }
    
    
    
    
    class func deserialize(from:JSON,accid:String)->ST_PairsUserCenterViewModel{
        
        let model = ST_PairsUserCenterViewModel()
        
        model.tableHeaderViewModel.accid = accid
        
        model.isSentProps = from["is_send_props"].boolValue
        
        let informationJson = from["information"]
        
        model.tableHeaderViewModel.voiceSignUrl = from["voice_sign_url"].url
        model.tableHeaderViewModel.voiceSignDuration = from["duration"].intValue
        
        model.tableHeaderViewModel.nickname = informationJson["nickname"].stringValue
        
        model.tableHeaderViewModel.nobilityImg = informationJson["nobility"]["image"].string
        
        if model.tableHeaderViewModel.accid == Defaults[.currentUserID] , let str = informationJson["nickname_auditing"].string,!str.isEmpty{
            model.tableHeaderViewModel.nickname = str
        }
        
        model.liveBeautyStatue = informationJson["newsletter_state"].intValue
        
        model.tableHeaderViewModel.isMyGuard = from["guard_member_accid"].stringValue == Defaults[.currentUserID]
        
        model.tableHeaderViewModel.guardTime = informationJson["guard_time"].intValue
        
        model.tableHeaderViewModel.vipExpire = informationJson["vip_expire"].intValue
        
        model.tableHeaderViewModel.guardContent = informationJson["guard_content"].stringValue
        
        let is_friend = from["is_friend"].boolValue
        
        if model.tableHeaderViewModel.accid != Defaults[.currentUserID],is_friend{
            
            model.is_friends = true
        }
        
        model.tableHeaderViewModel.age = informationJson["age"].intValue
        model.tableHeaderViewModel.online_state = informationJson["online_state"].stringValue
        model.tableHeaderViewModel.address = informationJson["address"].stringValue
        model.tableHeaderViewModel.distance = informationJson["distance"].stringValue
        model.tableHeaderViewModel.face_audit_state = informationJson["face_audit_state"].intValue
        model.tableHeaderViewModel.is_show_active = informationJson["is_show_active"].boolValue
        
        model.tableHeaderViewModel.is_attention = informationJson["is_attention"].boolValue
        
        model.tableHeaderViewModel.is_friends = informationJson["is_friend"].boolValue
        
        model.tableHeaderViewModel.sex = ST_SEX.init(rawValue: informationJson["gender"].intValue) ?? ST_SEX.unkown
        
        model.tableHeaderViewModel.sign = informationJson["sign"].stringValue
        
        if model.tableHeaderViewModel.accid == Defaults[.currentUserID] , let str = informationJson["sign_auditing"].string,!str.isEmpty{
            model.tableHeaderViewModel.sign = str
        }
        
        model.tableHeaderViewModel.guideModel = PairsGuardModel.init(json: from, avatar: from["album"][0]["content"].stringValue)
//        init(json: from)
        
        var genderStr = "他"
        
        if informationJson["gender"].intValue == 2{
            genderStr = "她"
        }
        
        if Defaults[.currentUserID] == informationJson["accid"].stringValue{
            genderStr = "我"
            model.tableHeaderViewModel.liked_num = informationJson["like_num"].intValue
        }
        
        model.ta = genderStr
        
        
        
            
            let Set = ST_PairsUserCenterSetionSet()
            
            Set.list = [ST_PairsCenterMatchloadingCellModel()]
            
            Set.displayFooter = false
            
            Set.displayHeader = false
            
            model.datasets.append(Set)
            
            let dailyList = from["daily_data"].arrayValue.map { (item) -> DailyOfSpaceCenterModel in
                return DailyOfSpaceCenterModel.init(fromJson: item)
            }
            //        日常
            if dailyList.count > 0{
                
                let dailySet = ST_PairsUserCenterSetionSet()
                dailySet.head.text = genderStr+"的日常"
                dailySet.head.sectionHeight += 2
                dailySet.footer.text = "查看更多"
                dailySet.footer.sectionHeight = 70
                
                let m =  ST_PairsOwnDailySetsModel()
                
                m.data = dailyList.first
                
                m.pairsCellHeight = dailyList.first?.cellHeight  ?? 10
                
                dailySet.list = [m]
                
                model.datasets.append(dailySet)
            }
            
            
            var own_feature = from["own_feature"].arrayValue.map { (item) -> ST_PairsPeculiarity in
                return ST_PairsPeculiarity.deserialize(from: item.rawString() ?? "") ??  ST_PairsPeculiarity()
            }
            
            if own_feature.count > 0{
                
                //        拥有的特质
                let ownSet = ST_PairsUserCenterSetionSet()
                ownSet.head.text = genderStr+"拥有的特质"
                ownSet.head.sectionHeight += 2
                ownSet.list = own_feature.map({ (p) -> ST_PairsPeculiarity in
                    
                    p.cellType = .peculiarityDetail
                    
                    p.pairsCellHeight = 73+200
                    
                    if p.remark.isEmpty{
                        p.pairsCellHeight -=  20
                    }
                    
                    return p
                })
                model.datasets.append(ownSet)
            }
            
        
        
        
        
        
        
        
        //        =======================自我介绍开始=========================
        
        var personal_desc = informationJson["personal_desc"].string
        
        
        
        if model.tableHeaderViewModel.accid == Defaults[.currentUserID] ,let str = informationJson["personal_desc_auditing"].string,!str.isEmpty{
            personal_desc = str
        }
        
        if let str = personal_desc,!str.isEmpty{
            
            let intro = ST_PairsUserCenterSetionSet()
            intro.head.text = "自我介绍"
            intro.head.sectionHeight += 2
            let dict20 = ST_PairsInfoModel()
            dict20.modifyKey = "personal_desc"
            dict20.displayKey = "自我介绍"
            dict20.displayValue = str
            
            let introAttrString = NSMutableAttributedString(string: str)
            
            let parg = NSMutableParagraphStyle()
            parg.lineSpacing = 5
            
            let introAttr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold),.foregroundColor: UIColor.init(hex: 0x61666F)!,.paragraphStyle:parg]
            
            introAttrString.addAttributes(introAttr, range: NSRange(location: 0, length: introAttrString.length))
            
            dict20.displayValueAttribute = introAttrString
            
            dict20.cellType = .text
            
            dict20.pairsCellHeight = introAttrString.height(withConstrainedWidth: ScreenWidth - 16 * 2) + 10
            
            
            intro.list = [dict20]
            
            
            model.datasets.append(intro)
        }
        
        
        
        //        =======================自我介绍结束=========================
        
        
        
        
        
        //        =======================个人资料开始=========================
        let info = ST_PairsUserCenterSetionSet()
        
        info.head.text = "个人资料"
        info.head.sectionHeight += 2
        model.datasets.append(info)
        
        //        基本资料
        var infoList = [ST_PairsInfoModel]()
        
        let dict2 = ST_PairsInfoModel()
        
        let attrString = NSMutableAttributedString(string: "基本资料")
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold),.foregroundColor: UIColor.init(hex: 0x333333)!]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        dict2.displayValueAttribute = attrString
        
        dict2.cellType = .subTitle
        
        dict2.pairsCellHeight = 20 + 22
        
        infoList.append(dict2)
        
        if let str = informationJson["nickname"].string,!str.isEmpty{
            
            let dict20 = ST_PairsInfoModel()
            dict20.modifyKey = "nickname"
            dict20.displayKey = "昵称"
            dict20.displayValue = str
            
            infoList.append(dict20)
        }
        
        
        let ageDict = ST_PairsInfoModel()
        ageDict.modifyKey = "age"
        ageDict.displayKey = "年龄"
        ageDict.displayValue = informationJson["age"].intValue.string + "岁"
        infoList.append(ageDict)
        
        
        let gender = informationJson["gender"].intValue
        
        let dict20 = ST_PairsInfoModel()
        dict20.modifyKey = "gender"
        dict20.displayKey = "性别"
        dict20.displayValue = gender == 1 ? "男" : "女"
        infoList.append(dict20)
        
        if let str = informationJson["constellation"].string,!str.isEmpty{
            
            let dict20 = ST_PairsInfoModel()
            dict20.modifyKey = "constellation"
            dict20.displayKey = "星座"
            dict20.displayValue = str
            
            infoList.append(dict20)
        }
        
        if let str = informationJson["personal_want_name"].string,!str.isEmpty{
            
            let dict20 = ST_PairsInfoModel()
            dict20.modifyKey = "personal_want"
            dict20.displayKey = "想要寻求"
            dict20.displayValue = str
            
            infoList.append(dict20)
        }
        
        
        if let str = informationJson["home_town_title"].string,!str.isEmpty{
            
            let dict20 = ST_PairsInfoModel()
            dict20.modifyKey = "home_town_title"
            dict20.displayKey = "家乡"
            dict20.displayValue = str
            
            infoList.append(dict20)
        }
        
        //        学历
        //        职业
        //        身高
        if !informationJson["personal_education_name"].stringValue.isEmpty ||  !informationJson["personal_job_name"].stringValue.isEmpty || !informationJson["height"].stringValue.isEmpty{
            
            let dict3 = ST_PairsInfoModel()
            
            let attrString3 = NSMutableAttributedString(string: "学历·职业·身高")
            
            attrString3.addAttributes(attr, range: NSRange(location: 0, length: attrString3.length))
            
            dict3.displayValueAttribute = attrString3
            
            dict3.cellType = .subTitle
            
            dict3.pairsCellHeight = 20 + 22
            
            infoList.append(dict3)
            
        }
        
        
        if let str = informationJson["personal_education_name"].string,!str.isEmpty{
            
            let dict20 = ST_PairsInfoModel()
            dict20.modifyKey = "personal_education_name"
            dict20.displayKey = "学历"
            dict20.displayValue = str
            
            infoList.append(dict20)
        }
        
        
        
        if let str = informationJson["personal_job_name"].string,!str.isEmpty{
            
            let dict20 = ST_PairsInfoModel()
            dict20.modifyKey = "personal_job_name"
            dict20.displayKey = "职业"
            dict20.displayValue = str
            
            infoList.append(dict20)
        }
        
        
        if let str = informationJson["height"].string,!str.isEmpty{
            
            let dict20 = ST_PairsInfoModel()
            dict20.modifyKey = "height"
            dict20.displayKey = "身高"
            dict20.displayValue = str
            
            infoList.append(dict20)
        }
        
        
        
        
        //        生活习惯
        if !informationJson["personal_smoke_name"].stringValue.isEmpty ||  !informationJson["personal_drink_name"].stringValue.isEmpty {
            
            let dict3 = ST_PairsInfoModel()
            
            let attrString3 = NSMutableAttributedString(string: "生活习惯")
            
            attrString3.addAttributes(attr, range: NSRange(location: 0, length: attrString3.length))
            
            dict3.displayValueAttribute = attrString3
            
            dict3.cellType = .subTitle
            
            dict3.pairsCellHeight = 20 + 22
            
            infoList.append(dict3)
            
        }
        
        
        if let str = informationJson["personal_smoke_name"].string,!str.isEmpty{
            
            let dict20 = ST_PairsInfoModel()
            dict20.modifyKey = "personal_smoke_name"
            dict20.displayKey = "抽烟"
            dict20.displayValue = str
            
            infoList.append(dict20)
        }
        
        
        
        if let str = informationJson["personal_drink_name"].string,!str.isEmpty{
            
            let dict20 = ST_PairsInfoModel()
            dict20.modifyKey = "personal_drink_name"
            dict20.displayKey = "喝酒"
            dict20.displayValue = str
            
            infoList.append(dict20)
        }
        
        info.list = infoList
        
        //        =======================个人资料结束=========================
        return model
    }
    
    
}

class ST_PairsUserCenterSetionSet: NSObject {
    
    var head = ST_PairsUserCenterSectionModel()
    
    var list = [ST_CellTypeProtocol]()
    
    lazy var footer:ST_PairsUserCenterSectionModel = {
        let m = ST_PairsUserCenterSectionModel()
        m.sectionHeight = 35
        return m
    }()
    
    //    展示 section Header
    var displayHeader = true
    //    展示 section footer
    var displayFooter = true
}

class ST_PairsUserCenterSectionModel {
    
    var text:String = ""
    
    //    var isCorner:Bool = false
    var accid = ""
    var ta = ""
    var sectionHeight = 52.cgFloat
}

/*
 /**
 个人中心Model
 */
 class ST_PairsUserModel: NSObject,HandyJSON {
 
 var liked_num = 0
 
 var like_feature_total = 0
 
 var is_friend = false
 
 var like_feature: Array<ST_PairsPeculiarity> = []
 
 var dailyList: Array<DailyOfSpaceCenterModel> = []
 
 var own_feature: Array<ST_PairsPeculiarity> = []
 
 required override init() {
 super.init()
 }
 
 
 
 //个人主页 组装数据
 func paddingOtherPeopleData(viewModel model:ST_PairsUserCenterViewModel,informationJson:JSON){
 
 }
 
 
 }
 */

/**
 新版 我拥有特质
 */
class ST_PairsLovePeculiaritySetsModel:NSObject, ST_CellTypeProtocol {
    
    var cellType: ST_PairsCenterCellType = .peculiaritySection
    
    var pairsCellHeight: CGFloat = 10
    
    var data_array = [ST_PairsPeculiarity]()
    
    var showMoreDataBtn = false
    
    var accid = ""
    /**
     我 他 或者 她
     */
    var ta = ""
}



/**
 新版 拥有日常
 */
class ST_PairsOwnDailySetsModel:NSObject, ST_CellTypeProtocol {
    
    var cellType: ST_PairsCenterCellType = .daily
    
    var pairsCellHeight: CGFloat = 10
    
    var data:DailyOfSpaceCenterModel?
    
}

/**
 特质
 */
class ST_PairsPeculiarity:NSObject,HandyJSON,ST_CellTypeProtocol {
    
    var pairsCellHeight: CGFloat = 60+15
    
    var cellType: ST_PairsCenterCellType = .peculiaritySection
    
    
    var image = ""
    var id = 0
    var pid = 0
    var name = ""
    var remark = ""
    var descriptionStr = ""
    var is_conform = false
    
    var detail: Array<ST_PairsPeculiarityContent> = []
    
    var view_count = 0
    
    var thumb_up_count = 0
    
    required override init() {
        super.init()
    }
    
    
    func mapping(mapper: HelpingMapper) {
        // specify 'description' field in json map to 'descriptionStr' property in object
        mapper <<<
            self.descriptionStr <-- "description"
    }
    
}


/**
 添加特质
 */
class ST_PairsAppendPeculiarity: ST_PairsPeculiarity {
    
}


/**
 空特质
 */
class ST_PairsEmptyPeculiarity: ST_PairsPeculiarity {
    
}
/**
 特质内容
 */
class ST_PairsPeculiarityContent: NSObject,HandyJSON {
    
    var content = ""
    var width:Float = 1
    var height:Float = 1
    
    var state = 0
    required override init() {
        super.init()
    }
}

/**
 个人信息
 */
class ST_PairsInfoModel: ST_EditGeneralInfoCellModel,ST_CellTypeProtocol {
    
    
    //    默认
    var pairsCellHeight: CGFloat = 36
    
    var cellType: ST_PairsCenterCellType = .textMap
}

